package com.example.goodpet.community.activity;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.FileProvider;
import androidx.fragment.app.FragmentActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.example.goodpet.R;
import com.example.goodpet.activity.adapter.UploadImageAdapter;
import com.example.goodpet.activity.enigne.GlideEngine;
import com.example.goodpet.bean.CommunityTiezi;
import com.example.goodpet.bean.ResponseBody;
import com.example.goodpet.my.activity.MyReleaseActivity;
import com.example.goodpet.release.activity.ReleasePetInformationActivity;
import com.example.goodpet.service.CommunityService;
import com.example.goodpet.utils.ActivityManager;
import com.example.goodpet.utils.ImageUtil;
import com.example.goodpet.utils.MyApplication;
import com.example.goodpet.utils.RetrofitSingleton;
import com.example.goodpet.utils.UIUtils;
import com.iceteck.silicompressorr.SiliCompressor;
import com.luck.picture.lib.basic.PictureSelector;
import com.luck.picture.lib.config.SelectMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.interfaces.OnResultCallbackListener;
import com.zackratos.ultimatebarx.ultimatebarx.java.UltimateBarX;

import java.io.File;
import java.io.IOException;
import java.sql.Date;
import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class ReleaseTieziActivity extends FragmentActivity implements View.OnClickListener {
    private LinearLayout pickPhoto;
    private EditText edContent;
    private RecyclerView recyclerView;
    private TextView tvCancel;
    private TextView submit;
    private ProgressDialog progressDialog;

    private List<Bitmap> localImage;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_release_tiezi);
        UltimateBarX.statusBarOnly(this)
                .fitWindow(true)
                .colorRes(R.color.ic_back_background)
                .light(true)
                .apply();
        ActivityManager.getInstance().addActivity(this);

        progressDialog=new ProgressDialog(this);
        progressDialog.setCancelable(false);
        progressDialog.setTitle("提示");
        progressDialog.setMessage("正在发布中");
        pickPhoto=findViewById(R.id.pickPhoto);
        edContent=findViewById(R.id.edContent);
        recyclerView=findViewById(R.id.recyclerView);
        tvCancel=findViewById(R.id.tvCancel);
        submit=findViewById(R.id.tvSubmit);

        GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 3);
        recyclerView.setLayoutManager(gridLayoutManager);
        localImage=new ArrayList<>();
        initListener();
    }

    private void initListener() {
        pickPhoto.setOnClickListener(this);
        tvCancel.setOnClickListener(this);
        submit.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        if (v.getId()==R.id.tvCancel){
            ActivityManager.getInstance().removeCurrent();
        }else if (v.getId()==R.id.tvSubmit){
            upLoad();
        }else if (v.getId()==R.id.pickPhoto){
            pickPhoto();
        }

    }

    /**
     * 从本地图库选择图片，并添加进localImage
     */
    private void pickPhoto() {
        PictureSelector.create(this)
                .openGallery(SelectMimeType.ofImage())
                .setImageEngine(GlideEngine.createGlideEngine())
                .setMaxSelectNum(9)
                .isDisplayCamera(false)
                .forResult(new OnResultCallbackListener<LocalMedia>() {
                    @Override
                    public void onResult(ArrayList<LocalMedia> result) {
                        for (int i = 0; i < result.size(); i++) {
                            String path = result.get(i).getPath();
                            try {
                                //sdk>=29返回content类型，其他返回绝对路径
                                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                                    localImage.add(SiliCompressor.with(ReleaseTieziActivity.this).
                                            getCompressBitmap(path));
                                } else {
                                    //处理返回绝对路径时
                                    Uri uri;
                                    File file = new File(path);
                                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                                        uri = FileProvider.getUriForFile(ReleaseTieziActivity.this, "com.example.goodpet.fileProvider", file);
                                    } else uri = Uri.fromFile(file);
                                    localImage.add(SiliCompressor.with(ReleaseTieziActivity.this).
                                            getCompressBitmap(String.valueOf(uri)));
                                }
                            }catch (IOException e) {
                                e.printStackTrace();
                            }

                            recyclerView.setAdapter(new UploadImageAdapter(localImage));
                        }
                    }
                    @Override
                    public void onCancel() {
                        //取消选择图片
                    }
                });
    }

    /**
     * 向服务端上传数据
     */
    private void upLoad() {
        progressDialog.show();
        if (TextUtils.isEmpty(edContent.getText().toString())){
            UIUtils.toast("内容不能为空哦！",false);
            return;
        }
        if (localImage.size()==0){
            UIUtils.toast("图片不能为空哦！",false);
            return;
        }
        //配置帖子信息
        CommunityTiezi communityTiezi = new CommunityTiezi();
        communityTiezi.setContent(edContent.getText().toString());
        communityTiezi.setPostdate(new Date(System.currentTimeMillis()));
        communityTiezi.setSenderId(MyApplication.user.getId());
        if (!localImage.isEmpty()){
            List<String> image=new ArrayList<>();
            for (int i=0; i<localImage.size(); i++ )
                image.add(ImageUtil.ImageToString(localImage.get(i)));
            communityTiezi.setImage(image);
        }
        //发送网络请求
        CommunityService communityService = RetrofitSingleton.getRetrofitConstance().create(CommunityService.class);
        communityService.uploadTieziInfo(communityTiezi).enqueue(new Callback<ResponseBody<String>>() {
            @Override
            public void onResponse(Call<ResponseBody<String>> call, Response<ResponseBody<String>> response) {
                progressDialog.dismiss();
                ResponseBody<String> body = response.body();
                if (body!=null)
                    if (body.getCode()==200){
                        new AlertDialog.Builder(ReleaseTieziActivity.this)
                                .setTitle("提示")
                                .setMessage("上传成功了，要去看看吗？")
                                .setNegativeButton("不用了", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        dialog.cancel();
                                    }
                                })
                                .setPositiveButton("去看看", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        ActivityManager.getInstance().removeCurrent();
                                        Intent intent = new Intent(ReleaseTieziActivity.this, MyReleaseActivity.class);
                                        intent.putExtra("position",1);
                                        startActivity(intent);
                                    }
                                }).show();
                    }else if (body.getCode()==500){
                        UIUtils.toast("不好意思，上传失败",false);
                    }
            }
            @Override
            public void onFailure(Call<ResponseBody<String>> call, Throwable t) {
                progressDialog.dismiss();
                UIUtils.toast("连接服务器失败！",false);
            }
        });
    }
}